package com.thinklib.util;

import com.thinklib.bean.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import javax.crypto.SecretKey;
import java.util.Date;
import java.util.UUID;

public class JwtUtils {

    /**
     * 过期时间，默认168小时，一周时间
     */
    public static final long EXPIRATION = 1000 * 60 * 60 * 24 * 7;

    /**
     * 加密密钥：必须足够长，否则不满足jwt安全要求
     */
    public static final String SECRET = "{88888888888888888888888888888888888888888888888888AtmSpin88888888888888888888888888888888888888888888888888}";

    /**
     * 令牌前缀
     */
    private static final String TOKEN_PREFIX = "thinklib";

    /**
     * 主题：颁发签名的网站
     */
    public static final String SUBJECT = "thinklib.com";

    // JWT加密
    public static String jwtEncryption(User user) {
        byte[] decode = Decoders.BASE64.decode(SECRET);
        SecretKey secretKey = Keys.hmacShaKeyFor(decode);
        String token = Jwts.builder()
                .setSubject(SUBJECT)
                .claim("id", user.getId())
                .claim("nickname", user.getNickname())
                .claim("avatar", user.getAvatar())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION))
                .setId(UUID.randomUUID().toString())
                .signWith(secretKey,SignatureAlgorithm.HS512)
                .compact();
        token = TOKEN_PREFIX + token;
        return token;
    }

    // JWT解密
    public static Claims jwtDecryption(String token) {
        try {
            final Claims claim = Jwts.parserBuilder().setSigningKey(SECRET).build().parseClaimsJws(token.replace(TOKEN_PREFIX,"")).getBody();
            return claim;
        } catch (Exception e) {
            return null;
        }
    }
}
